package o2o.web.actions.order.other;

import com.jinyou.utils.common.*;
import jPush.dao.JPushMessage;
import notice.dao.NoticeType;
import o2o.cache.order.*;
import o2o.cache.postman.CityPostmanMemory;
import o2o.cache.sys.SysConfigDepositMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.cache.wallet.UserWalletMemory;
import o2o.config.dao.UserDaoSql;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.common.ResultInfo;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.order.*;
import o2o.postman.model.CityPostman;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.PO.wallet.UserWallet;
import o2o.dao.VO.order.OrderGoodsLabelVO;
import o2o.dao.VO.order.OrderInfoImageVO;
import o2o.dao.VO.order.OrderInfoPreAdminVO;
import o2o.dao.VO.order.OrderInfoPreVO;
import o2o.dao.VO.postman.CityPostmanVO;
import o2o.system.data.SYS_CONFIG_PATH;
import o2o.system.data.SYS_SETTINGS;
import o2o.task.jPush.JPushTask;
import o2o.task.mixComTel.MixComTelTask;
import o2o.utils.OrderUtils;
import o2o.web.actions.notice.Notice;
import o2o.web.actions.order.OrderMan;
import o2o.web.actions.order.image.OrderImageMan;
import o2o.web.actions.postman.PostmanMan;
import o2o.web.actions.user.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

//订单（老克用）
@Controller
public class ServiceOrderAction {

    //获取某一订单详情
    @RequestMapping(method = RequestMethod.POST, value = "/user/service/order/info")
    @ResponseBody
    public String user_order_info(String token, String orderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //订单信息
        OrderInfoPreVO infoVO = getOrderDetail(orderNo);
        if (null == infoVO) {
            return AjaxResult.errorResult("当前订单不存在请查证");
        }

        return AjaxResult.successResult(infoVO);
    }

    //获取某一订单详情 管理后台
    @RequestMapping(method = RequestMethod.POST, value = "/service/order/info")
    @ResponseBody
    public String order_info(String token, String orderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        OrderInfoPreVO infoVO = getOrderDetail(orderNo);
        if (null == infoVO) {
            return AjaxResult.errorResult("当前订单不存在请查证");
        }

        if (ValidateUtil.isNotNull(infoVO.getUsername())) {
            CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(infoVO.getUsername());
            CityPostmanVO postmanVO = PostmanMan.getOne(cityPostman);
            infoVO.setSubmitPostman(postmanVO);
        }


        return AjaxResult.successResult(infoVO);
    }


    //-----------------锁匠
    //锁匠下单
    @RequestMapping(method = RequestMethod.POST, value = "/user/serviceOrder/submit")
    @ResponseBody
    public String order_submit(String token, String sysAppKey,
                               Integer isAppointment, Long ziQuTime,
                               Integer isUrgent,
                               String name, String phone,
                               Double lat, Double lng,
                               String province, String city, String county, String address, String address2, String address3,
                               String note, String extra1, String extra2, String extra3,
                               String labelsJson) {

        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

//        if (0 == UserType.POSTMAN - user.getUserType()) {
//            return AjaxResult.errorResult("您不是锁匠，无法发包");
//        }

        CityPostman postman = CityPostmanMemory.getInstance().getPostman(user.getUsername());
        if (null == postman) {
            return AjaxResult.errorResult("未查询到您的信息，无法操作");
        }
        //0 锁定  1未锁定
        if (null != postman.getIsLock() && 0 == 1 - postman.getIsLock()) {
            return AjaxResult.errorResult("您已被锁定，无法发单");
        }
        if (ValidateUtil.isNotAbsInteger(postman.getIsWork())) {
            return AjaxResult.errorResult("您无法接单，请先上班");
        }
        if (0 == postman.getIsWork()) {
            return AjaxResult.errorResult("请先上班");
        }

        if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY
                && (null == postman.getIsVerify() || 0 != 1 - postman.getIsVerify())) {
            return AjaxResult.errorResult("您尚未通过认证，请先去认证");
        }
        if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE) {
            if (null != user.getIsCert() && 0 == 1 - user.getIsCert()) {
                //已认证
            } else {
                return AjaxResult.errorResult("未通过实名认证，请先去认证");
            }
        }

        if (null != SYS_SETTINGS.POSTMAN_MUST_DEPOSIT && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_DEPOSIT) {
            // 必须缴纳
            //验证押金金额是否满足
            UserWallet userWallet = UserWalletMemory.getInstance().getWallet(user.getUsername());
            if (null == userWallet) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金");
            }
            if (null == userWallet.getDepositMoney() || userWallet.getDepositMoney() <= 0) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金！");
            }
            //必须缴纳的押金金额
            Double money = SysConfigDepositMemory.getInstance().getByType(UserType.POSTMAN);
            if (null == money) {
                money = 0d;
            }

            if (JYMathDoubleUtils.sub(userWallet.getDepositMoney(), money) < 0) {
                return AjaxResult.errorResult("您缴纳的押金不足，请先缴纳押金");
            }
        }

        OrderSubmitResult result = submitOrder(sysAppKey,
                user, UserType.POSTMAN,
                null,
                isAppointment, ziQuTime,
                isUrgent,
                name, phone,
                lat, lng,
                province, city, county, address, address2, address3,
                note, extra1, extra2, extra3,
                labelsJson);
        if (null != result && result.isSuccess()) {
            return AjaxResult.successResult(result);
        } else {
            return AjaxResult.errorResult(result.getError());
        }
    }

    //查看自己已发布订单
    @RequestMapping(method = RequestMethod.POST, value = "/user/serviceOrder/list")
    @ResponseBody
    public String order_own_list(String token, Long createTime, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        CityPostman postman = CityPostmanMemory.getInstance().getPostman(user.getUsername());
        if (null == postman) {
            return AjaxResult.errorResult("未查询到您的信息，无法操作");
        }

        if (null == createTime) {
            createTime = 0l;
        }
        if (null == size) {
            size = 20;
        }

        List<OrderInfoPre> list = OrderInfoPreMemory.getInstance().listOfUser(user.getUsername(), createTime, size);
        List<OrderInfoPreVO> voList = new ArrayList<>();
        if (ValidateUtil.isAbsList(list)) {
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }

                OrderInfoPreVO vo = new OrderInfoPreVO();
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), vo, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                if (null == vo) {
                    continue;
                }

//                //获取配送员抢单信息
//                List<OrderGrabInfo> grabInfoList = PostmanGrabMemory.getInstance().grabListOfOrder(orderInfoAdminVO.getOrderNo());
//                if (ValidateUtil.isAbsList(grabInfoList)) {
//                    orderInfoAdminVO.setGrabInfo(grabInfoList);
//                }

                if (ValidateUtil.isNotNull(vo.getShopImageUrl()) && ValidateUtil.isNotNetUrl(vo.getShopImageUrl())) {
//                    vo.setShopImageUrl(Common.imageUrl + vo.getShopImageUrl());
                    vo.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + vo.getShopImageUrl());
                }
                if (ValidateUtil.isNotNull(vo.getPostmanImageUrl()) && ValidateUtil.isNotNetUrl(vo.getPostmanImageUrl())) {
//                    vo.setPostmanImageUrl(Common.imageUrl + vo.getPostmanImageUrl());
                    vo.setPostmanImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + vo.getPostmanImageUrl());
                }


                //开锁订单显示收益
                if (0 == ORDER_TYPE.SERVICE_LOCK - vo.getOrderType()) {
                    Double money = 0d;
                    OrderPayInfo payInfo = OrderPayMemory.getInstance().get(vo.getOrderNo());
//                    if (null != payInfo) {
//                        money = payInfo.getPostmanMoney();
//                    }
//                    if (ValidateUtil.isNotNull(vo.getPostManUsername()) && user.getUsername().equalsIgnoreCase(vo.getPostManUsername())) {
//                        money = JYMathDoubleUtils.add(money, payInfo.getPostmanMoney());
//                    }

                    if (null != payInfo) {
                        money = payInfo.getShopMoney();
                        vo.setTotalPrice(payInfo.getTotalPrice());
                        vo.setTotalMoney(payInfo.getTotalPrice());
                    }
                    vo.setShopMoney(money);
                }
                voList.add(vo);
            }


            return AjaxResult.successResult(voList.size(), voList);
        }

        return AjaxResult.successResult(0, 0, null);
    }


    //取消我发布的工单
    @RequestMapping(method = RequestMethod.POST, value = "/user/serviceOrder/cancel")
    @ResponseBody
    public String order_postman_cancel(String token, String orderNo, String cancelReason) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        ResultInfo resultInfo = cancelOrder(user, orderNo, cancelReason);
        if (null != resultInfo) {
            if (!resultInfo.isSuccess()) {
                return AjaxResult.errorResult(resultInfo.getError());
            }
        } else {
            return AjaxResult.errorResult("取消失败，请稍后再试");
        }

//        if (ValidateUtil.isNull(orderNo)) {
//            return AjaxResult.errorResult("请选择订单");
//        }
//
//        OrderInfoPre orderInfo = OrderInfoPreMemory.getInstance().getOrderInfo(orderNo);
//        if (null == orderInfo) {
//            return AjaxResult.errorResult("该订单不存在");
//        }
//
//        //是配送员的话判断一下这个订单是不是他的
//        if (0 == UserType.POSTMAN - user.getUserType() && ValidateUtil.isNotNull(orderInfo.getUsername()) && !user.getUsername().equalsIgnoreCase(orderInfo.getUsername())) {
//            return AjaxResult.errorResult("该订单不是您的，您无法取消");
//        }
//
//        //判断订单状态是否可以操作
//        if (ORDER_STATUS.SUBMIT != orderInfo.getOrderStatus()) {
//            return AjaxResult.errorResult("该状态不允许操作");
//        }
//
//
//        Long time = DateUtils.getCurrTime();
//        //修改订单状态为配送员已接单
//        //修改数据库
//        StringBuilder sb = new StringBuilder();
//        sb.append("update ").append(PojoTables.ORDER_INFO_PRE).append(" set orderStatus = ").append(ORDER_STATUS.CANCEL)
//                .append(",updateUser='").append(user.getUsername()).append("',postmanFinishTime=").append(time).append(",cancelReason='").append(cancelReason).append("'")
//                .append(" where delFlag=0 and orderNo = '").append(orderNo).append("'");
//        try {
//            UserDaoSql.getInstance().executeBySql(sb.toString());
//        } catch (SQLException e) {
//            e.printStackTrace();
//            return AjaxResult.errorResult("操作失败，请稍后重试");
//        }
//
//        //修改缓存
//        OrderInfoPreMemory.getInstance().modifyStatus(orderNo);

        return AjaxResult.successResult();
    }


    //-------------------客服
    //查看锁匠已发布订单  客服
    @RequestMapping(method = RequestMethod.POST, value = "/service/order/unPublish/list")
    @ResponseBody
    public String order_unDelivery_list(String token, String city, String county, String region, Long createTime, int size, Integer isLoadMore) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (!User.hasServiceAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有权限");
        }

        if (ValidateUtil.isNotAbsLong(createTime)) {
            createTime = 0l;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }

        if (ValidateUtil.isNotAbsInteger(isLoadMore)) {
            isLoadMore = 0;
        }

        List<OrderInfoPre> list = OrderInfoPreMemory.getInstance().cityUnDeliveryList(city, county, region, createTime, size, isLoadMore);
        List<OrderInfoPreAdminVO> orderInfoAdminVOList = new ArrayList<>();
        if (ValidateUtil.isAbsList(list)) {
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }

                OrderInfoPreAdminVO orderInfoAdminVO = new OrderInfoPreAdminVO();
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), orderInfoAdminVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                if (null == orderInfoAdminVO) {
                    continue;
                }

//                //获取配送员抢单信息
//                List<OrderGrabInfo> grabInfoList = PostmanGrabMemory.getInstance().grabListOfOrder(orderInfoAdminVO.getOrderNo());
//                if (ValidateUtil.isAbsList(grabInfoList)) {
//                    orderInfoAdminVO.setGrabInfo(grabInfoList);
//                }

                if (ValidateUtil.isNotNull(orderInfoAdminVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoAdminVO.getShopImageUrl())) {
//                    orderInfoAdminVO.setShopImageUrl(Common.imageUrl + orderInfoAdminVO.getShopImageUrl());
                    orderInfoAdminVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoAdminVO.getShopImageUrl());
                }
                if (ValidateUtil.isNotNull(orderInfoAdminVO.getPostmanImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoAdminVO.getPostmanImageUrl())) {
//                    orderInfoAdminVO.setPostmanImageUrl(Common.imageUrl + orderInfoAdminVO.getPostmanImageUrl());
                    orderInfoAdminVO.setPostmanImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoAdminVO.getPostmanImageUrl());
                }
                orderInfoAdminVOList.add(orderInfoAdminVO);
            }


            return AjaxResult.successResult(orderInfoAdminVOList.size(), orderInfoAdminVOList);
        }

        return AjaxResult.successResult(0, 0, null);
    }

    //编辑下单


//    //配送员获取最新订单
//    @RequestMapping(method = RequestMethod.POST, value = "/service/postman/order/new/list")
//    @ResponseBody
//    public String order_postman_new_list(String token, Long createTime, int size, Integer isLoadMore) {
//        //验证用户有效性
//        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
//        if (user == null) {
//            return AjaxResult.errorLogoutResult();
//        }
//        if (!User.hasServiceAuth(user.getUserType())) {
//            return AjaxResult.errorResult("您没有权限查看");
//        }
//
//        //是否为加载更多，0不是，1是
//        if (ValidateUtil.isNotAbsInteger(isLoadMore)) {
//            isLoadMore = 0;
//        }
//
//        if (ValidateUtil.isNotAbsLong(createTime)) {
//            createTime = 0l;
//        }
//        if (ValidateUtil.isNotAbsInteger(size)) {
//            size = 20;
//        }
//        //获取配送员所有未接订单
//        List<OrderInfoPre> list = OrderInfoPreMemory.getInstance().listOfPostmanNew(user.getUsername(), createTime, size, isLoadMore);
//        if (ValidateUtil.isAbsList(list)) {
//            List<OrderInfoPreVO> voList = new ArrayList<>();
//            for (int i = 0; i < list.size(); i++) {
//                if (null == list.get(i)) {
//                    continue;
//                }
//                OrderInfoPreVO orderInfoVO = new OrderInfoPreVO();
//                try {
//                    ObjectUtils.copyPropertiesExclude(list.get(i), orderInfoVO, null);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    continue;
//                }
//                if (null == orderInfoVO) {
//                    continue;
//                }
//                if (ValidateUtil.isNotNull(orderInfoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
//                    orderInfoVO.setShopImageUrl(Common.imageUrl + orderInfoVO.getShopImageUrl());
//                }
//
//                voList.add(orderInfoVO);
//            }
//
//            if (ValidateUtil.isAbsList(voList)) {
//                return AjaxResult.successResult(voList.size(), voList);
//            }
//        }
//
//
//        //无最新指定订单，返回待抢订单
//        CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(user.getUsername());
//        if (null != cityPostman) {
//            //获取该城市订单
//            List<OrderInfo> orderList = OrderInfoMemory.getInstance().cityUnDeliveryList(cityPostman.getCity(), cityPostman.getCounty(), cityPostman.getRegion(), createTime, size, isLoadMore);
//
//            if (ValidateUtil.isAbsInteger(SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT)) {
//                if (0 == POSTMAN_IN_CITY_OR_AGENT_DATA.CITY - SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT) {//按城市获取
//                    orderList = OrderInfoMemory.getInstance().cityUnDeliveryList(cityPostman.getCity(), cityPostman.getCounty(), cityPostman.getRegion(), createTime, size, isLoadMore);
//                } else if (0 == POSTMAN_IN_CITY_OR_AGENT_DATA.AGENT - SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT) {//按代理获取
//                    Long agentId = PostmanAgentRelationMemory.getInstance().getAgentByPostmanUsername(user.getUsername());
//                    orderList = OrderInfoMemory.getInstance().agentUnDeliveryList(agentId, createTime, size, isLoadMore);
//                }
//            } else {//默认按城市
//                orderList = OrderInfoMemory.getInstance().cityUnDeliveryList(cityPostman.getCity(), cityPostman.getCounty(), cityPostman.getRegion(), createTime, size, isLoadMore);
//            }
//
//
//            if (ValidateUtil.isAbsList(orderList)) {
//                List<OrderInfoVO> orderInfoVOList = new ArrayList<OrderInfoVO>();
//                for (int i = 0; i < orderList.size(); i++) {
//                    if (null == orderList.get(i)) {
//                        continue;
//                    }
//
//                    OrderInfoVO orderInfoVO = new OrderInfoVO();
//                    try {
//                        ObjectUtils.copyPropertiesExclude(orderList.get(i), orderInfoVO, null);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        continue;
//                    }
//                    if (null == orderInfoVO) {
//                        continue;
//                    }
//                    if (ValidateUtil.isNotNull(orderInfoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
//                        orderInfoVO.setShopImageUrl(Common.imageUrl + orderInfoVO.getShopImageUrl());
//                    }
//                    orderInfoVOList.add(orderInfoVO);
//                }
//                return AjaxResult.successResult(orderInfoVOList.size(), orderInfoVOList);
//            }
//        }
//
//        return AjaxResult.successResult(0, null);
//    }
//

    //客服人员下单
    @RequestMapping(method = RequestMethod.POST, value = "/admin/serviceOrder/submit")
    @ResponseBody
    public String admin_order_submit(String token, String sysAppKey,
                                     String preOrderNo, String cancelOrderNo,
                                     Integer isAppointment, Long ziQuTime,
                                     Integer isUrgent,
                                     String name, String phone,
                                     Double lat, Double lng,
                                     String province, String city, String county, String address, String address2, String address3,
                                     String note, String extra1, String extra2, String extra3,
                                     String labelsJson) {

        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (!User.hasServiceAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有发布权限");
        }

        if (null != user && User.isLocked(user.getIsLock())) {
            return AjaxResult.errorResult("您已被锁定，无法操作");
        }

        if (ValidateUtil.isNotNull(cancelOrderNo)) {//重新下单 需要取消之前的订单
            OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(cancelOrderNo);
            if (null != orderInfo) {
                if (0 == 1 - orderInfo.getIsPaid()) {
                    return AjaxResult.errorResult("订单已支付，无法重新下单");
                }
                ResultInfo resultInfo = OrderMan.cancelOrderDirect(orderInfo, user.getUsername(), "", ORDER_STATUS.CANCEL, true, true);
                if (null != resultInfo) {
                    if (!resultInfo.isSuccess()) {
                        return AjaxResult.errorResult(resultInfo.getError());
                    }
                } else {
                    return AjaxResult.errorResult("重新下单失败，请稍后再试！");
                }


                //删除就行了
                StringBuffer sb = new StringBuffer();
                sb.append("update ").append(PojoTables.OrderInfo).append(" set delFlag = 1 ,updateUser='")
                        .append(user.getUsername()).append("' where delFlag = 0 and orderNo = '").append(cancelOrderNo).append("'");
                try {
                    UserDaoSql.getInstance().executeBySql(sb.toString());
                } catch (SQLException e) {
                    e.printStackTrace();
                    return AjaxResult.errorResult("重新下单失败，请稍后再试。");
                }

                //解绑小号
                MixComTelTask.unbindMap.put(cancelOrderNo, cancelOrderNo);
            }
        }


        OrderSubmitResult result = submitOrder(sysAppKey,
                user, user.getUserType(),
                preOrderNo,
                isAppointment, ziQuTime,
                isUrgent,
                name, phone,
                lat, lng,
                province, city, county, address, address2, address3,
                note, extra1, extra2, extra3,
                labelsJson);
        if (null != result && result.isSuccess()) {
            return AjaxResult.successResult(result);
        } else {
            return AjaxResult.errorResult(result.getError());
        }
    }

    //取消工人发布的工单
    @RequestMapping(method = RequestMethod.POST, value = "/admin/serviceOrder/cancel")
    @ResponseBody
    public String order_cancel(String token, String orderNo, String cancelReason) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        ResultInfo resultInfo = cancelOrder(user, orderNo, cancelReason);
        if (null != resultInfo) {
            if (!resultInfo.isSuccess()) {
                return AjaxResult.errorResult(resultInfo.getError());
            }
        } else {
            return AjaxResult.errorResult("取消失败，请稍后再试");
        }

        //解绑小号
        MixComTelTask.unbindMap.put(orderNo, orderNo);
//        if (ValidateUtil.isNull(orderNo)) {
//            return AjaxResult.errorResult("请选择订单");
//        }
//
//        OrderInfoPre orderInfo = OrderInfoPreMemory.getInstance().getOrderInfo(orderNo);
//        if (null == orderInfo) {
//            return AjaxResult.errorResult("该订单不存在");
//        }
//
//        //是配送员的话判断一下这个订单是不是他的
//        if (0 == UserType.POSTMAN - user.getUserType() && ValidateUtil.isNotNull(orderInfo.getUsername()) && !user.getUsername().equalsIgnoreCase(orderInfo.getUsername())) {
//            return AjaxResult.errorResult("该订单不是您的，您无法取消");
//        }
//
//        //判断订单状态是否可以操作
//        if (ORDER_STATUS.SUBMIT != orderInfo.getOrderStatus()) {
//            return AjaxResult.errorResult("该状态不允许操作");
//        }
//
//
//        Long time = DateUtils.getCurrTime();
//        //修改订单状态为配送员已接单
//        //修改数据库
//        StringBuilder sb = new StringBuilder();
//        sb.append("update ").append(PojoTables.ORDER_INFO_PRE).append(" set orderStatus = ").append(ORDER_STATUS.CANCEL)
//                .append(",updateUser='").append(user.getUsername()).append("',postmanFinishTime=").append(time).append(",cancelReason='").append(cancelReason).append("'")
//                .append(" where delFlag=0 and orderNo = '").append(orderNo).append("'");
//        try {
//            UserDaoSql.getInstance().executeBySql(sb.toString());
//        } catch (SQLException e) {
//            e.printStackTrace();
//            return AjaxResult.errorResult("操作失败，请稍后重试");
//        }
//
//        //修改缓存
//        OrderInfoPreMemory.getInstance().modifyStatus(orderNo);

        return AjaxResult.successResult();
    }


    //---------------------------------------
    //提交订单
    private OrderSubmitResult submitOrder(String sysAppKey,
                                          UserInfo user, int submitUserType,
                                          String preOrderNo,
                                          Integer isAppointment, Long ziQuTime,
                                          Integer isUrgent,
                                          String name, String phone,
                                          Double lat, Double lng,
                                          String province, String city, String county, String address, String address2, String address3,
                                          String note, String extra1, String extra2, String extra3,
                                          String labelsJson) {
        OrderSubmitResult orderSubmitResult = new OrderSubmitResult();

        String subUsername = user.getUsername();
        String orderNo = null;
        OrderInfo orderInfo = new OrderInfo();
        if (ValidateUtil.isNotNull(preOrderNo)) {
            orderNo = preOrderNo;
            //编辑预订单 发布到平台
            OrderInfoPre orderInfoPre = OrderInfoPreMemory.getInstance().getOrderInfo(preOrderNo);
            if (null == orderInfoPre) {
                orderSubmitResult.setSuccess(false);
                orderSubmitResult.setError("该订单已不存在，请查证");
                return orderSubmitResult;
            }
            subUsername = orderInfoPre.getUsername();
//            OrderInfo orderInfo = new OrderInfo();
//            try {
//                ObjectUtils.copyPropertiesExclude(orderInfoPre, orderInfo, null);
//            } catch (Exception e) {
//                e.printStackTrace();
//                orderSubmitResult.setSuccess(false);
//                orderSubmitResult.setError("发布失败，请稍后再试");
//                return orderSubmitResult;
//            }
            orderInfo.setServiceUsername(user.getUsername());
        } else {
            orderNo = OrderUtils.getOrderNo();
            orderInfo.setShopName(user.getName());
            orderInfo.setShopPhone(user.getTelPhone());
            orderInfo.setShopImageUrl(user.getSignPhoto());
        }

        if (null != isAppointment && 0 == 1 - isAppointment && (null == ziQuTime || ziQuTime < 1)) {
            orderSubmitResult.setSuccess(false);
            orderSubmitResult.setError("请先选择预约时间");
            return orderSubmitResult;
        }


        if (ValidateUtil.isNull(city)) {
            orderSubmitResult.setSuccess(false);
            orderSubmitResult.setError("请先选择城市");
            return orderSubmitResult;
        }
//        if (ValidateUtil.isNotAbsDouble(lat) || ValidateUtil.isNotAbsDouble(lng)) {
        if (ValidateUtil.isNotLatLng(lat, lng)) {
            orderSubmitResult.setSuccess(false);
            orderSubmitResult.setError("请先选择详细地址");
            return orderSubmitResult;
        }
        if (ValidateUtil.isNull(address)) {
            orderSubmitResult.setSuccess(false);
            orderSubmitResult.setError("请先填写详细地址");
            return orderSubmitResult;
        }

        if (ValidateUtil.isNull(phone)) {
            orderSubmitResult.setSuccess(false);
            orderSubmitResult.setError("请先输入手机号");
            return orderSubmitResult;
        }

        if (ValidateUtil.isNull(labelsJson)) {
            orderSubmitResult.setSuccess(false);
            orderSubmitResult.setError("请先选择服务类型");
            return orderSubmitResult;
        }


        Long time = DateUtils.getCurrTime();


        boolean isOrder = false;
        String labelTable = PojoTables.ORDER_GOODS_LABEL_PRE;
        String table = PojoTables.ORDER_INFO_PRE;
        switch (submitUserType) {
            case UserType.POSTMAN: {
                isOrder = false;
                table = PojoTables.ORDER_INFO_PRE;
                labelTable = PojoTables.ORDER_GOODS_LABEL_PRE;
            }
            break;
            case UserType.CUSTOMER_SERVICE:
            case UserType.SUPER_ADMIN:
            case UserType.ADMIN: {
                isOrder = true;
                table = PojoTables.OrderInfo;
                labelTable = PojoTables.ORDER_GOODS_LABEL;

                if (ValidateUtil.isNotNull(preOrderNo)) {//转单
                    orderInfo.setShopId(-4l);//工人发单
                } else {
                    orderInfo.setShopId(-3l);//平台发单
                }
            }
            break;
        }



        if (null == isUrgent) {
            isUrgent = 0;
        }
        if (null == isAppointment) {
            isAppointment = 0;
        }

        //保存对应的订单信息
        orderInfo.setOrderStatus(ORDER_STATUS.SUBMIT);
        orderInfo.setOrderType(ORDER_TYPE.SERVICE_LOCK);//订单类型，跑腿订单
        orderInfo.setOrderNo(orderNo);
        orderInfo.setCreateTime(time);
        orderInfo.setCreateUser(user.getUsername());
        orderInfo.setDelFlag(0);

        orderInfo.setTotalPrice(0d);
        orderInfo.setTotalMoney(0d);
        orderInfo.setUsername(subUsername);
        orderInfo.setCity(city);
        orderInfo.setProvince(province);
        orderInfo.setCounty(county);
        orderInfo.setLat(lat);
        orderInfo.setLng(lng);
//        orderInfo.setDeliveryId(toAddress.getId());
        orderInfo.setBuyer(name);
        orderInfo.setTelephone(phone);
        orderInfo.setAddress(address);
        if (ValidateUtil.isNotNull(address2) && "null".equalsIgnoreCase(address2)) {
            address2 = "";
        }
        if (ValidateUtil.isNotNull(address3) && "null".equalsIgnoreCase(address3)) {
            address3 = "";
        }
        if (null == address2) {
            address2 = "";
        }
        if (null == address3) {
            address3 = "";
        }
        if (ValidateUtil.isNotNull(address3)) {
            orderInfo.setAddress2(address2 + " " + address3);
        } else {
            orderInfo.setAddress2(address2);
        }


        orderInfo.setShopCity(city);
        orderInfo.setIsZiQu(0);


        orderInfo.setIsZiQu(1);
        orderInfo.setZiQuTime(ziQuTime);
        orderInfo.setIsAppointment(isAppointment);//是否预约
        orderInfo.setIsComment(0);//是否已评价
        orderInfo.setUserDel(0);//是否已删除 0未删，1删除
        orderInfo.setIsUrgent(isUrgent);//是否加急
        orderInfo.setNote(note);//订单备注
        orderInfo.setExtra1(extra1);//备用字段1
        orderInfo.setExtra2(extra2);//备用字段2
        orderInfo.setExtra3(extra3);//备用字段3

        try {
            UserDaoSql.getInstance().insertObj(table, orderInfo);
        } catch (SQLException e) {
            e.printStackTrace();
            orderSubmitResult.setSuccess(false);
            orderSubmitResult.setError("存储订单信息失败，请稍后再试");
            return orderSubmitResult;
        }

        if (isOrder) {
            OrderInfoMemory.getInstance().addOrderInfo(orderNo);

            //4. 订单状态保存
            OrderStatus orderStatus = new OrderStatus();
            orderStatus.setOrderNo(orderNo);
            orderStatus.setCreateUser(user.getUsername());
            orderStatus.setCreateTime(DateUtils.getCurrTime());
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, orderStatus);
            } catch (SQLException e) {
                e.printStackTrace();
                orderSubmitResult.setSuccess(false);
                orderSubmitResult.setError("存储订单信息失败，请稍后再试。");
                return orderSubmitResult;
            }
            //5.3 缓存订单状态信息
            OrderStatusMemory.getInstance().addStatus(orderNo);

            //检测是否在规定时间内支付
//            OrderInfo oInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
//            OrderThread.map.put(orderNo, oInfo);


            //更新订单已被转单
            updatePreOrder(orderNo, user.getUsername(), user.getUsername());


            //推给该城市的锁匠
            if (null != orderInfo.getOrderType() && 0 == ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType()) {
                JPushMessage jPushMessage = new JPushMessage(true, city, "又有新的订单了", "又有新的订单了，快去抢单吧");
                jPushMessage.setPushUserType(JPushMessage.POSTMAN);//推给配送员
                jPushMessage.setJpSubType("");
                JPushTask.jPushMessageList.add(jPushMessage);

            }
        } else {
            OrderInfoPreMemory.getInstance().addOrderInfo(orderNo);

            //发送一条订单通知
//            Notice.publishOrderNotice(user.getUsername(), "订单信息", "您的订单已提交");
//
//            //极光推送
//            JPushMessage jPushMessage2 = new JPushMessage(user.getUsername(), "订单信息", "您的订单已提交");
//            jPushMessage2.setPushUserType(JPushMessage.USER);//推给用户
//            JPushTask.jPushMessageList.add(jPushMessage2);

            Notice.publishNotice2Person(sysAppKey, user.getUsername(), JPushMessage.USER, NoticeType.order, "又有新的订单了", "您的订单已提交");
        }

//        //如果是工人发单 则需要更改状态
//        String shopReadyTime = ",shopReadyTime=" + DateUtils.getCurrTime();
//        Order.modifyPreOrderStatus(user.getUsername(), orderNo, ORDER_STATUS.SHOP_READY, shopReadyTime, null);

        orderSubmitResult.setSuccess(true);
        orderSubmitResult.setOrderNo(orderNo);
        return orderSubmitResult;

    }

    //获取订单详情
    private OrderInfoPreVO getOrderDetail(String orderNo) {
        //订单信息
        OrderInfoPre info = OrderInfoPreMemory.getInstance().getOrderInfo(orderNo);
        if (null == info) {
            return null;
        }
        OrderInfoPreVO infoVO = new OrderInfoPreVO();
        try {
            ObjectUtils.copyPropertiesExclude(info, infoVO, null);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //标签信息
        List<OrderGoodsLabelPre> labelList = OrderGoodsLabelPreMemory.getInstance().listOfOrderNo(orderNo);
        if (ValidateUtil.isAbsList(labelList)) {
            List<OrderGoodsLabelVO> labelVOList = new ArrayList<>();
            for (int i = 0; i < labelList.size(); i++) {
                if (null == labelList.get(i)) {
                    continue;
                }
                OrderGoodsLabelVO vo = new OrderGoodsLabelVO();
                try {
                    ObjectUtils.copyPropertiesExclude(labelList.get(i), vo, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                labelVOList.add(vo);
            }
            infoVO.setLabelList(labelVOList);
        }

        //服务内容
        List<OrderItems> itemList = OrderItemsMemory.getInstance().listOfOrderNo(orderNo);
        if (ValidateUtil.isAbsList(labelList)) {
            infoVO.setItemList(itemList);
        }

        //图片信息
        List<OrderInfoImageVO> imageList = OrderImageMan.listOfOrderNo(orderNo);
        infoVO.setImageList(imageList);

        return infoVO;
    }

    //取消工单
    private ResultInfo cancelOrder(UserInfo user, String orderNo, String cancelReason) {
        if (ValidateUtil.isNull(orderNo)) {
            return new ResultInfo("请选择订单");
        }

        OrderInfoPre orderInfo = OrderInfoPreMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return new ResultInfo("该订单不存在");
        }

        //是配送员的话判断一下这个订单是不是他的
        if (0 == UserType.POSTMAN - user.getUserType() && ValidateUtil.isNotNull(orderInfo.getUsername()) && !user.getUsername().equalsIgnoreCase(orderInfo.getUsername())) {
            return new ResultInfo("该订单不是您的，您无法取消");
        }

        //判断订单状态是否可以操作
        if (ORDER_STATUS.SUBMIT != orderInfo.getOrderStatus()) {
            return new ResultInfo("该状态不允许操作");
        }


        Long time = DateUtils.getCurrTime();
        //修改订单状态为配送员已接单
        //修改数据库
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.ORDER_INFO_PRE).append(" set orderStatus = ").append(ORDER_STATUS.CANCEL)
                .append(",updateUser='").append(user.getUsername()).append("',postmanFinishTime=").append(time).append(",cancelReason='").append(cancelReason).append("'")
                .append(" where delFlag=0 and orderNo = '").append(orderNo).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultInfo("操作失败，请稍后重试");
        }

        //修改缓存
        OrderInfoPreMemory.getInstance().modifyStatus(orderNo);
        return new ResultInfo();
    }

    //已被转单
    private boolean updatePreOrder(String orderNo, String serviceUsername, String opUsername) {
        //订单信息
        OrderInfoPre info = OrderInfoPreMemory.getInstance().getOrderInfo(orderNo);
        if (null == info) {
            return false;
        }

        Long time = DateUtils.getCurrTime();
        StringBuffer sb = new StringBuffer();
        sb.append("update ").append(PojoTables.ORDER_INFO_PRE).append(" set updateUser='").append(opUsername).append("',serviceUsername='").append(serviceUsername).append("',serviceSureTime=").append(time).append(" where delFlag = 0 and orderNo = '").append(orderNo).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }

        OrderInfoPreMemory.getInstance().modifyStatus(orderNo);

        return true;
    }
}
